// CSS 格式化工具渲染器
window.CSSFormatterRenderer = class CSSFormatterRenderer {
    static getHTML() {
        return `
            <h2 class="text-3xl font-bold text-gray-800 mb-6">
                <i data-feather="code" class="w-8 h-8 inline mr-3 text-indigo-600"></i>
                CSS 格式化器
            </h2>
            <div class="bg-gray-50 rounded-lg p-4 mb-6">
                <p class="text-gray-600">专业的CSS格式化、压缩和验证工具，支持语法检查、自动修复和代码美化。</p>
            </div>
            
            <!-- 输入区域 -->
            <div class="bg-white rounded-xl shadow-sm border p-6 mb-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    <i data-feather="edit" class="w-5 h-5 inline mr-2"></i>
                    CSS 输入
                </h3>
                
                <div class="mb-4">
                    <textarea 
                        id="css-input" 
                        rows="12" 
                        placeholder="粘贴或输入CSS代码..."
                        class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent font-mono text-sm resize-y"
                    ></textarea>
                </div>
                
                <!-- 操作按钮 -->
                <div class="flex flex-wrap gap-3 mb-4">
                    <button 
                        id="format-css" 
                        class="bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center"
                    >
                        <i data-feather="align-left" class="w-4 h-4 mr-2"></i>
                        格式化
                    </button>
                    <button 
                        id="minify-css" 
                        class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center"
                    >
                        <i data-feather="minimize-2" class="w-4 h-4 mr-2"></i>
                        压缩
                    </button>
                    <button 
                        id="validate-css" 
                        class="bg-orange-600 hover:bg-orange-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center"
                    >
                        <i data-feather="check-circle" class="w-4 h-4 mr-2"></i>
                        验证
                    </button>
                    <button 
                        id="auto-fix-css" 
                        class="bg-purple-600 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center"
                    >
                        <i data-feather="tool" class="w-4 h-4 mr-2"></i>
                        自动修复
                    </button>
                    <button 
                        id="clear-css" 
                        class="bg-gray-100 hover:bg-gray-200 text-gray-700 font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center"
                    >
                        <i data-feather="trash-2" class="w-4 h-4 mr-2"></i>
                        清空
                    </button>
                </div>
                
                <!-- 格式化选项 -->
                <details class="mb-4">
                    <summary class="cursor-pointer text-sm font-medium text-gray-700 hover:text-gray-900">
                        <i data-feather="settings" class="w-4 h-4 inline mr-1"></i>
                        格式化选项
                    </summary>
                    <div class="mt-3 p-4 bg-gray-50 rounded-lg">
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">缩进大小</label>
                                <select id="indent-size" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 text-sm">
                                    <option value="2">2个空格</option>
                                    <option value="4">4个空格</option>
                                    <option value="tab">制表符</option>
                                </select>
                            </div>
                            <div>
                                <label class="flex items-center space-x-2 text-sm">
                                    <input type="checkbox" id="braces-same-line" class="form-checkbox text-indigo-600">
                                    <span>大括号同行</span>
                                </label>
                            </div>
                            <div>
                                <label class="flex items-center space-x-2 text-sm">
                                    <input type="checkbox" id="add-semicolon" checked class="form-checkbox text-indigo-600">
                                    <span>添加分号</span>
                                </label>
                            </div>
                            <div>
                                <label class="flex items-center space-x-2 text-sm">
                                    <input type="checkbox" id="trim-whitespace" checked class="form-checkbox text-indigo-600">
                                    <span>移除尾随空白</span>
                                </label>
                            </div>
                            <div>
                                <label class="flex items-center space-x-2 text-sm">
                                    <input type="checkbox" id="final-newline" checked class="form-checkbox text-indigo-600">
                                    <span>文件末尾换行</span>
                                </label>
                            </div>
                        </div>
                    </div>
                </details>
            </div>

            <!-- 结果区域 -->
            <div id="css-result" class="bg-white rounded-xl shadow-sm border p-6 mb-6 hidden">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold text-gray-800">
                        <i data-feather="file-text" class="w-5 h-5 inline mr-2"></i>
                        处理结果
                    </h3>
                    <div class="flex gap-2">
                        <button 
                            id="copy-result" 
                            class="bg-gray-100 hover:bg-gray-200 text-gray-700 font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center"
                        >
                            <i data-feather="copy" class="w-4 h-4 mr-2"></i>
                            复制
                        </button>
                        <button 
                            id="download-result" 
                            class="bg-gray-100 hover:bg-gray-200 text-gray-700 font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center"
                        >
                            <i data-feather="download" class="w-4 h-4 mr-2"></i>
                            下载
                        </button>
                    </div>
                </div>
                
                <div class="mb-4">
                    <textarea 
                        id="css-output" 
                        rows="12" 
                        readonly
                        class="w-full px-4 py-3 border border-gray-300 rounded-lg bg-gray-50 font-mono text-sm resize-y"
                    ></textarea>
                </div>
            </div>

            <!-- 验证结果区域 -->
            <div id="validation-result" class="bg-white rounded-xl shadow-sm border p-6 mb-6 hidden">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    <i data-feather="alert-circle" class="w-5 h-5 inline mr-2"></i>
                    验证结果
                </h3>
                <div id="validation-content">
                    <!-- 动态生成验证结果 -->
                </div>
            </div>

            <!-- 统计信息区域 -->
            <div id="css-stats" class="bg-white rounded-xl shadow-sm border p-6 hidden">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    <i data-feather="bar-chart-2" class="w-5 h-5 inline mr-2"></i>
                    统计信息
                </h3>
                <div id="stats-content" class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
                    <!-- 动态生成统计信息 -->
                </div>
            </div>
        `;
    }

    static init() {
        // 获取DOM元素
        const cssInput = document.getElementById('css-input');
        const cssOutput = document.getElementById('css-output');
        const formatBtn = document.getElementById('format-css');
        const minifyBtn = document.getElementById('minify-css');
        const validateBtn = document.getElementById('validate-css');
        const autoFixBtn = document.getElementById('auto-fix-css');
        const clearBtn = document.getElementById('clear-css');
        const copyBtn = document.getElementById('copy-result');
        const downloadBtn = document.getElementById('download-result');
        
        // 选项元素
        const indentSizeSelect = document.getElementById('indent-size');
        const bracesSameLineCheckbox = document.getElementById('braces-same-line');
        const addSemicolonCheckbox = document.getElementById('add-semicolon');
        const trimWhitespaceCheckbox = document.getElementById('trim-whitespace');
        const finalNewlineCheckbox = document.getElementById('final-newline');

        // 当前操作类型
        let currentOperation = null;

        // 加载示例
        this.loadExample();

        // 格式化按钮
        formatBtn.addEventListener('click', () => {
            const css = cssInput.value.trim();
            if (!css) {
                DevToolsUtils.showToast('请输入CSS代码', 'error');
                return;
            }

            const options = this.getFormatOptions();
            const result = CSSFormatter.formatCSS(css, options);
            
            if (result.success) {
                currentOperation = 'format';
                this.displayResult(result.data.formatted, result.data.stats);
                DevToolsUtils.showToast('CSS格式化成功', 'success');
            } else {
                DevToolsUtils.showToast(result.error, 'error');
            }
        });

        // 压缩按钮
        minifyBtn.addEventListener('click', () => {
            const css = cssInput.value.trim();
            if (!css) {
                DevToolsUtils.showToast('请输入CSS代码', 'error');
                return;
            }

            const result = CSSFormatter.minifyCSS(css);
            
            if (result.success) {
                currentOperation = 'minify';
                this.displayResult(result.data.minified, result.data.stats);
                DevToolsUtils.showToast('CSS压缩成功', 'success');
            } else {
                DevToolsUtils.showToast(result.error, 'error');
            }
        });

        // 验证按钮
        validateBtn.addEventListener('click', () => {
            const css = cssInput.value.trim();
            if (!css) {
                DevToolsUtils.showToast('请输入CSS代码', 'error');
                return;
            }

            const result = CSSFormatter.validateCSS(css);
            
            if (result.success) {
                this.displayValidationResult(result.data);
                DevToolsUtils.showToast('CSS验证完成', 'success');
            } else {
                DevToolsUtils.showToast(result.error, 'error');
            }
        });

        // 自动修复按钮
        autoFixBtn.addEventListener('click', () => {
            const css = cssInput.value.trim();
            if (!css) {
                DevToolsUtils.showToast('请输入CSS代码', 'error');
                return;
            }

            const result = CSSFormatter.autoFixCSS(css);
            
            if (result.success) {
                currentOperation = 'autofix';
                this.displayResult(result.data.fixed, result.data.stats);
                this.displayFixesSummary(result.data.fixes);
                DevToolsUtils.showToast('CSS自动修复完成', 'success');
            } else {
                DevToolsUtils.showToast(result.error, 'error');
            }
        });

        // 清空按钮
        clearBtn.addEventListener('click', () => {
            cssInput.value = '';
            this.hideResults();
        });

        // 复制结果
        copyBtn.addEventListener('click', () => {
            const result = cssOutput.value;
            if (!result) {
                DevToolsUtils.showToast('没有结果可复制', 'error');
                return;
            }
            
            DevToolsUtils.copyToClipboard(result);
            DevToolsUtils.showToast('结果已复制', 'success');
        });

        // 下载结果
        downloadBtn.addEventListener('click', () => {
            const result = cssOutput.value;
            if (!result) {
                DevToolsUtils.showToast('没有结果可下载', 'error');
                return;
            }
            
            const filename = currentOperation === 'minify' ? 'formatted.min.css' : 'formatted.css';
            this.downloadFile(result, filename, 'text/css');
            DevToolsUtils.showToast('文件已下载', 'success');
        });

        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey && e.key === 'Enter') {
                e.preventDefault();
                formatBtn.click();
            }
        });

        // 初始化 Feather Icons
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 100);
    }

    static getFormatOptions() {
        const indentSize = document.getElementById('indent-size').value;
        const bracesSameLine = document.getElementById('braces-same-line').checked;
        const addSemicolon = document.getElementById('add-semicolon').checked;
        const trimWhitespace = document.getElementById('trim-whitespace').checked;
        const finalNewline = document.getElementById('final-newline').checked;
        
        return {
            indentSize: indentSize === 'tab' ? 1 : parseInt(indentSize),
            indentType: indentSize === 'tab' ? 'tab' : 'space',
            bracesOnSameLine: bracesSameLine,
            addSemicolon: addSemicolon,
            trimTrailingWhitespace: trimWhitespace,
            insertFinalNewline: finalNewline
        };
    }

    static displayResult(result, stats) {
        const resultDiv = document.getElementById('css-result');
        const outputTextarea = document.getElementById('css-output');
        
        outputTextarea.value = result;
        resultDiv.classList.remove('hidden');
        
        if (stats) {
            this.displayStats(stats);
        }
        
        // 滚动到结果区域
        resultDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }

    static displayStats(stats) {
        const statsDiv = document.getElementById('css-stats');
        const statsContent = document.getElementById('stats-content');
        
        const isMinified = stats.savings > 0;
        
        statsContent.innerHTML = `
            <div class="text-center">
                <div class="text-2xl font-bold text-blue-600">${stats.originalSize.toLocaleString()}</div>
                <div class="text-sm text-gray-600">原始大小(字符)</div>
            </div>
            <div class="text-center">
                <div class="text-2xl font-bold text-green-600">${stats.processedSize.toLocaleString()}</div>
                <div class="text-sm text-gray-600">处理后大小(字符)</div>
            </div>
            ${isMinified ? `
            <div class="text-center">
                <div class="text-2xl font-bold text-purple-600">${stats.savings.toLocaleString()}</div>
                <div class="text-sm text-gray-600">节省字符数</div>
            </div>
            <div class="text-center">
                <div class="text-2xl font-bold text-orange-600">${stats.savingsPercentage}%</div>
                <div class="text-sm text-gray-600">压缩率</div>
            </div>
            ` : ''}
            <div class="text-center">
                <div class="text-2xl font-bold text-indigo-600">${stats.processedRules}</div>
                <div class="text-sm text-gray-600">CSS规则数</div>
            </div>
            <div class="text-center">
                <div class="text-2xl font-bold text-gray-600">${stats.processedProps}</div>
                <div class="text-sm text-gray-600">属性数</div>
            </div>
        `;
        
        statsDiv.classList.remove('hidden');
    }

    static displayValidationResult(validationData) {
        const validationDiv = document.getElementById('validation-result');
        const validationContent = document.getElementById('validation-content');
        
        const { isValid, errors, warnings, summary } = validationData;
        
        let html = `
            <div class="mb-4 p-4 rounded-lg ${isValid ? 'bg-green-50 border border-green-200' : 'bg-red-50 border border-red-200'}">
                <div class="flex items-center">
                    <i data-feather="${isValid ? 'check-circle' : 'x-circle'}" class="w-5 h-5 ${isValid ? 'text-green-600' : 'text-red-600'} mr-2"></i>
                    <span class="font-medium ${isValid ? 'text-green-800' : 'text-red-800'}">${summary}</span>
                </div>
            </div>
        `;
        
        if (errors.length > 0) {
            html += `
                <div class="mb-4">
                    <h4 class="font-medium text-red-800 mb-2 flex items-center">
                        <i data-feather="alert-triangle" class="w-4 h-4 mr-2"></i>
                        错误 (${errors.length})
                    </h4>
                    <div class="space-y-2">
                        ${errors.map(error => `
                            <div class="bg-red-50 border border-red-200 rounded p-3">
                                <div class="flex justify-between items-start">
                                    <span class="text-red-700">${error.message}</span>
                                    <span class="text-red-500 text-sm">行 ${error.line}</span>
                                </div>
                            </div>
                        `).join('')}
                    </div>
                </div>
            `;
        }
        
        if (warnings.length > 0) {
            html += `
                <div class="mb-4">
                    <h4 class="font-medium text-yellow-800 mb-2 flex items-center">
                        <i data-feather="alert-circle" class="w-4 h-4 mr-2"></i>
                        警告 (${warnings.length})
                    </h4>
                    <div class="space-y-2">
                        ${warnings.map(warning => `
                            <div class="bg-yellow-50 border border-yellow-200 rounded p-3">
                                <div class="flex justify-between items-start">
                                    <span class="text-yellow-700">${warning.message}</span>
                                    <span class="text-yellow-500 text-sm">行 ${warning.line}</span>
                                </div>
                            </div>
                        `).join('')}
                    </div>
                </div>
            `;
        }
        
        validationContent.innerHTML = html;
        validationDiv.classList.remove('hidden');
        
        // 更新图标
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 50);
        
        // 滚动到验证结果
        validationDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }

    static displayFixesSummary(fixes) {
        if (fixes.length === 0) return;
        
        const validationDiv = document.getElementById('validation-result');
        const validationContent = document.getElementById('validation-content');
        
        const html = `
            <div class="mb-4 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                <h4 class="font-medium text-blue-800 mb-2 flex items-center">
                    <i data-feather="tool" class="w-4 h-4 mr-2"></i>
                    自动修复 (${fixes.length})
                </h4>
                <ul class="space-y-1">
                    ${fixes.map(fix => `
                        <li class="text-blue-700 text-sm">• ${fix}</li>
                    `).join('')}
                </ul>
            </div>
        `;
        
        validationContent.innerHTML = html;
        validationDiv.classList.remove('hidden');
        
        // 更新图标
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 50);
    }

    static hideResults() {
        document.getElementById('css-result').classList.add('hidden');
        document.getElementById('validation-result').classList.add('hidden');
        document.getElementById('css-stats').classList.add('hidden');
    }

    static loadExample() {
        const example = `.header{background:#3b82f6;color:white;padding:20px 0}
.nav ul{list-style:none;margin:0;padding:0;display:flex}
.nav li{margin:0 15px}.nav a{color:white;text-decoration:none}
.nav a:hover{text-decoration:underline}
.content{max-width:1200px;margin:0 auto;padding:40px 20px}
.btn{display:inline-block;background:#10b981;color:white;padding:12px 24px;border:none;border-radius:6px;cursor:pointer}
.btn:hover{background:#059669}`;
        
        document.getElementById('css-input').value = example;
    }

    static downloadFile(content, filename, mimeType) {
        const blob = new Blob([content], { type: mimeType });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
    }
};